package com.qf.utils;

import javax.sql.DataSource;
import java.sql.Connection;
import java.sql.SQLException;

/**
 * @Description: 公用常量
 * @Data: 2022/8/31 10:27
 * @Pacakge: com.qf.utils
 * @ClassName: ConnectionUtils
 * @Author: fan
 */
public class ConnectionUtils {
    //线程绑定
    private ThreadLocal<Connection> threadLocal = new ThreadLocal<Connection>();
    //获取数据源
    private DataSource dataSource ;
    //通过set注入
    public void setDataSource(DataSource dataSource) {
        this.dataSource = dataSource;
    }

    /**
     * 获取数据库连接对象
     * @return
     */
    public Connection getConnection(){
        //通过线程获取数据库连接对象
        Connection connection = threadLocal.get();
        //判断
        if (connection == null){
            try {
                //通过数据源获取数据库连接对象
                connection = dataSource.getConnection();
                //存入线程中
                threadLocal.set(connection);
            } catch (SQLException e) {
               new RuntimeException(e);
            }
        }
        return connection;
    }

    /**
     * 解绑
     */
    public void  removeConnection(){
        threadLocal.remove();
    }
}
